<!-- 健康数据展示 -->
<template>
  <div>
    <!-- <div @click="readFile">readFile</div> -->
    <!-- <div @click="test">aaaa</div> -->
    <div v-if="showCallDialog" class="dialogBigBox">
      <div :class="[isShowVedio ? 'vediodialogBox' : 'dialogBox']">
        <div class="dialogTitle">
          <i
            @click="removeUser"
            class="el-icon-close"
            style="position: absolute; right: 1rem; cursor: pointer"
          ></i>
        </div>
        <div>
          <img
            style="width: 20rem"
            src="../../assets/images/global/cannected.gif"
          />
        </div>
        <div style="text-align: right">
          <img
            @click="removeUser"
            style="
              width: 5rem;
              cursor: pointer;
              position: absolute;
              right: 2rem;
              bottom: 1rem;
            "
            src="../../assets/images/call/guaduan.png"
          />
        </div>
      </div>
    </div>

    <div
      class="[showCallDialog ? 'callBox' : 'nocallBox']"
      @click="changeScreen"
    >
      <div id="local_stream_intercom" :class="localClass"></div>
      <div v-for="(item, i) in remoteStream" :key="i">
        <div :class="distantClass" v-html="item"></div>
      </div>
    </div>
  </div>
</template>
<!-- <script src="../../../public/debug/log4javascript.js"></script>  -->
<!-- <script src="https://cdn.bootcdn.net/ajax/libs/log4javascript/1.4.9/log4javascript.min.js"></script> -->

<script>
import { mapState, mapMutations } from "vuex";
import TRTC from "trtc-js-sdk";
import { genTestUserSig } from "../../../public/debug/GenerateTestUserSig";
import config from "../../config";
import mqtt from "mqtt";
import {
  MQTT_SERVICE,
  MQTT_USERNAME,
  MQTT_PASSWORD,
} from "../../utils/sysconstant";
const roomoptions = {
  connectTimeout: 40000,
  clientId: "appmqttjs_" + Math.random().toString(16).substr(2, 8),
  username: MQTT_USERNAME,
  password: MQTT_PASSWORD,
  clean: true, //保留回话
};
import {
  terminalCreate,
  getTrtcLogin,
  trtcRemoveUser,
  // getTrtcRoomUser,
  getVideoParams,
} from "../../api/index";
// import { setTimeout } from "timers";
//import qs from "qs";
var logTimer = null;
var callingTimer = null; //开房间60倒计时
export default {
  name: "callRoom",

  computed: {
    ...mapState({
      hintprofile: (state) => state.hintprofile, //视频编码质量配置
      profile: (state) => state.profile, //视频清晰度配置
      audioprofile: (state) => state.audioprofile, //语音配置
      currentUserId: (state) => state.currentUserId, //当前的用户id
      loginUserInfo: (state) => state.loginUserInfo,
      userInfoDetails: (state) => state.userInfoDetails,
      isJoinRoom: (state) => state.isJoinRoom,
      callStatus: (state) => state.callStatus, //获取通话状态
      loginlogList: (state) => state.loginlogList, //日志内容
    }),
    localClass: function () {
      let localstyle = "";
      //如果是语音对讲
      if (!this.isShowVedio) {
        localstyle = "local-stream-audio";
      } else {
        //如果是视频对讲,并且自己是大屏
        if (this.myBigScreen) {
          localstyle = "local-stream-vedio";
        } else {
          localstyle = "distant-stream-vedio";
        }
      }
      return localstyle;
    },
    distantClass: function () {
      let distantstyle = "";
      //如果是语音对讲
      if (!this.isShowVedio) {
        distantstyle = "distant-stream-audio";
      } else {
        //如果是视频对讲,并且自己是大屏
        if (this.myBigScreen) {
          distantstyle = "distant-stream-vedio";
        } else {
          distantstyle = "local-stream-vedio";
        }
      }
      return distantstyle;
    },
  },

  data() {
    return {
      activaterMethod: "",
      joinTelName: "",
      callDurationsTimer: null, //通话时长计时器
      callDurations: 0, //通话时长
      hasOther: false, //是否有人进房
      hasRoom: false, //是否收到请求并创建房间
      callType: 1, //通话类型 1:语音  2：视频
      addUserTimer: null,
      isjoinRoom: false, //是否加入房间
      joinUserId: "", //加入房间的人的userId
      showCallDialog: false,
      remoteStream: [], //远方视频流
      localStreamIntercom: null, //本地流
      myBigScreen: false,
      isShowVedio: false, //是否展示视频通话
      localNetworkQuality: 0,
      isNetworkOnline: false,
      logList: "",
      logTimer: null, //日志更新计时器
      roomClient: null, //ws
      roomwsConnected: false, //ws是否连接
      joinTelNum: "", //请求加入房间的客户的手机号
      twoMinuesTimer: null, //倒计时两分钟离房
    };
  },

  created() {
    // this.log = log4javascript.getDefaultLogger();
    //获取的日志记录器将忽略所有日志记录请求，不会输出任何日志信息
    // this.log = log4javascript.getNullLogger()
    //获取登录状态的日志
    this.getLoginlogList();
    //创建TRTC
    //this.createTrtc();
    //登录TRTC
    this.loginTrtc();
    //获取网络状态
    //this.getNetworkStatus();
    //开启日志更新计时器
    //this.refreshLog();
    //获取视频参数
    this.getVideoParam();
    //创建mqtt连接
    this.roomMqttMSG();
  },
  watch: {
    // isNetworkOnline: function (newStatus, oldStatus) {
    //   //刚才是断网状态
    //   if (oldStatus == false && newStatus == true) {
    //     console.log(
    //       "断网后又连接成功10后判断是否需要重新进房。状态",
    //       newStatus,
    //       "旧状态",
    //       oldStatus
    //     );
    //     setTimeout(() => {
    //       this.log.info("断网后又连接成功，判断是否需要重新进房");
    //       this.logList +=
    //         new Date().Format("yyyy-MM-dd hh:mm:ss") +
    //         "  info - 断网后又连接成功，判断是否需要重新进房\n";
    //       this.getRoomUser();
    //     }, 10000);
    //   }
    // },
  },
  mounted() {
    console.log("=================mounted================");
    // this.refreshLog();
  },
  methods: {
    ...mapMutations([
      "setisJoinRoom", //设置通讯类型
      "setprofile", //设置视频参数
      "setaudioprofile", //设置语音参数
      "setHintProfile", //设置编码参数
      "updateCallStatus", //设置通话状态
    ]),
    getLoginlogList() {
      this.logList += this.loginlogList;
      console.log("获取登录页的日志数据", this.loginlogList);
    },
    //连接mq
    roomMqttMSG() {
      this.joinTelNum = ""; //初始化加入人的电话号码
      console.log("**************roomMqtt开始连接**************");
      // this.log.info("roomMqtt开始连接");
      this.logList +=
        new Date().Format("yyyy-MM-dd hh:mm:ss") +
        "  info - roomMqtt开始连接\n";

      let that = this;
      let currentUserId = this.currentUserId;
      that.roomClient = mqtt.connect(MQTT_SERVICE, roomoptions);
      if (!that.roomClient.connected) {
        // mqtt连接
        that.roomClient.on("connect", () => {
          console.log("roomMqtt连接成功");
          // that.log.info("roomMqtt连接成功");
          that.logList +=
            new Date().Format("yyyy-MM-dd hh:mm:ss") +
            "  info - roomMqtt连接成功\n";
          that.roomwsConnected = true; //ws连接成功
          let topic = currentUserId + "/surveillance/request";
          //连接成功后订阅消息
          that.roomClient.subscribe(topic, { qos: 0 }, (error) => {
            if (!error) {
              console.log("**************订阅成功**************");
            } else {
              console.log("**************订阅失败**************");
            }
          });
        });
      }
      // 接收消息处理
      that.roomClient.on("message", (topic, message) => {
        let data = JSON.parse(message);
        let callStatus = that.callStatus;
        // that.log.info("收到来自" + data.senderID + "的消息");
        that.logList +=
          new Date().Format("yyyy-MM-dd hh:mm:ss") +
          "  info - " +
          `收到来自${topic}的消息` +
          "\n";
        console.log("收到来自", topic, "的消息", data);
        console.log("是否已经创建房间", this.hasRoom, data.type == 0);
        //type:0: join 1: Leave
        if (data.type == 0) {
          //如果该人已经请求过，并且此刻有房间，返回房间号
          if (that.joinTelNum == data.senderID) {
            console.log("如果该人已经进过房了");
            if (this.hasRoom) {
              //此刻正在创建房间  或已经创好了房间
              // that.log.info("该用户上一次请求过进房，并且此时房间只有一个人");
              that.logList +=
                new Date().Format("yyyy-MM-dd hh:mm:ss") +
                "  info - 该用户上一次请求过进房，并且此时房间只有一个人\n";
              that.roomMqttPublish();
              return;
            } else {
              console.log("没有房间，当前通话状态", callStatus);
              //没有房间
              if (callStatus == "idle" || callStatus == "") {
                if (data.modeltype == 1) {
                  that.isShowVedio = false;
                } else {
                  that.isShowVedio = true;
                }
                //创建TRTC
                that.createTrtc();
              } else {
                //处于忙碌状态，回复拒绝加入的消息
                that.refusePublish(data.senderID);
              }
            }
          } else {
            //modeltype 1：语音  2：视频
            //如果是空闲状态，则创建房间
            if (callStatus == "idle" || callStatus == "") {
              if (data.modeltype == 1) {
                that.isShowVedio = false;
              } else {
                that.isShowVedio = true;
              }
              that.joinTelNum = data.senderID;
              that.joinTelName = data.senderName; //激活者姓名
              that.activaterMethod = data.senderType; //激活者方式
              //创建TRTC
              that.createTrtc();
            } else {
              //处于忙碌状态，回复拒绝加入的消息
              that.refusePublish(data.senderID);
            }
          }
        }
      });
      // 断开发起重连
      that.roomClient.on("reconnect", (error) => {
        // that.log.info("roomMqtt正在重连");
        that.logList +=
          new Date().Format("yyyy-MM-dd hh:mm:ss") +
          "  info - roomMqtt正在重连\n";
        console.log("正在重连:", error);
      });
      //如果连接错误，打印错误
      that.roomClient.on("error", function (err) {
        console.log("连接错误了 err=>", err);
        // that.log.error("roomMqtt连接错误");
        that.logList +=
          new Date().Format("yyyy-MM-dd hh:mm:ss") +
          "  error - " +
          `roomMqtt连接错误${err}` +
          "\n";
        if (that.roomwsConnected) {
          that.roomClient.end();
        }
        that.roomwsConnected = false;
      });
    },
    //发送拒绝消息
    refusePublish(data) {
      let topic = data + "/surveillance/response";
      //订阅后发送消息
      let mess = {
        clientID: data,
        modeltype: this.isShowVedio ? 2 : 1, //1：语音  2：视频
        Type: 0, //0: join 1: Leave
        roomID: this.currentUserId, //电话号码
        isAgree: 2, //1：同意  2：拒绝
        userID: this.currentUserId,
        responseTime: new Date().Format("yyyy-MM-dd hh:mm:ss"),
      };
      // this.log.info("当前处于忙碌状态，返回拒绝消息", topic);
      console.log("当前处于忙碌状态，返回拒绝消息", topic);
      this.logList +=
        new Date().Format("yyyy-MM-dd hh:mm:ss") +
        "  info - 当前处于忙碌状态，返回拒绝消息\n";
      this.roomClient.publish(topic, JSON.stringify(mess));
    },
    //发送同意消息
    roomMqttPublish() {
      this.showCallDialog = true; //展示弹窗
      let topic = this.joinTelNum + "/surveillance/response";
      //订阅后发送消息
      let mess = {
        clientID: this.joinTelNum,
        modeltype: this.isShowVedio ? 2 : 1, //1：语音  2：视频
        Type: 0, //0: join 1: Leave
        roomID: this.currentUserId, //电话号码
        isAgree: 1, //1：同意  2：拒绝
        userID: this.currentUserId,
        responseTime: new Date().Format("yyyy-MM-dd hh:mm:ss"),
      };
      this.updateCallStatus("connected");
      console.log("返回同意消息", topic);
      // this.log.info("返回同意消息", topic);
      this.logList +=
        new Date().Format("yyyy-MM-dd hh:mm:ss") + "  info - 返回同意消息\n";
      this.roomClient.publish(topic, JSON.stringify(mess));
    },
    readFile() {
      var childProcess = require("child_process");
      childProcess.exec("ls -a", function (error, stdout) {
        if (error) {
          console.log(error.stack);
          console.log("Error code: " + error.code);
        }
        console.log("输出内容是: " + stdout);
      });
    },
    activeLog() {
      console.log("调用心跳接口");
      // this.log.info("调用心跳接口");
      this.logList +=
        new Date().Format("yyyy-MM-dd hh:mm:ss") + "  info - 调用心跳接口\n";
    },
    //获取视频的参数配置
    async getVideoParam() {
      let userId = this.currentUserId;
      await getVideoParams(userId)
        .then((res) => {
          console.log("获取视频参数数据", res);
          if (res.code == 0) {
            let videoProfile = "";
            if (res.data.video_quanlity) {
              videoProfile = res.data.video_quanlity;
            } else if (localStorage.getItem("video_quanlity")) {
              videoProfile = localStorage.getItem("video_quanlity");
            } else {
              videoProfile = "480p";
            }
            let audioProfile = "";
            if (res.data.noise_quanlity) {
              audioProfile = res.data.noise_quanlity;
            } else if (localStorage.getItem("noise_quanlity")) {
              audioProfile = localStorage.getItem("noise_quanlity");
            } else {
              audioProfile = "standard";
            }
            let hintProfile = "";
            if (res.data.coding_quanlity) {
              hintProfile = res.data.coding_quanlity;
            } else if (localStorage.getItem("coding_quanlity")) {
              hintProfile = localStorage.getItem("coding_quanlity");
            } else {
              hintProfile = "default";
            }
            //let videoProfile = res.data.video_quanlity || "480p";
            //let audioProfile = res.data.noise_quanlity || "standard";
            //let hintProfile = res.data.coding_quanlity || "default";
            this.setprofile(videoProfile);
            this.setaudioprofile(audioProfile);
            this.setHintProfile(hintProfile);
          } else {
            console.log("获取视频参数失败：" + res.message);
            // this.log.error("获取视频参数失败：" + res.message);
            this.logList +=
              new Date().Format("yyyy-MM-dd hh:mm:ss") +
              "  error - " +
              `获取视频参数失败： ${res.message}` +
              "\n";
            let videoProfile = "";
            if (localStorage.getItem("video_quanlity")) {
              videoProfile = localStorage.getItem("video_quanlity");
              console.log("获取缓存中的视频参数：" + videoProfile);
              // this.log.info("获取缓存中的视频参数：" + videoProfile);
              this.logList +=
                new Date().Format("yyyy-MM-dd hh:mm:ss") +
                "  info - " +
                `获取缓存中的视频参数：${videoProfile}` +
                "\n";
            } else {
              videoProfile = "480p";
            }
            let audioProfile = "";
            if (localStorage.getItem("noise_quanlity")) {
              audioProfile = localStorage.getItem("noise_quanlity");
            } else {
              audioProfile = "standard";
            }
            let hintProfile = "";
            if (localStorage.getItem("coding_quanlity")) {
              hintProfile = localStorage.getItem("coding_quanlity");
            } else {
              hintProfile = "default";
            }
            this.setprofile(videoProfile);
            this.setaudioprofile(audioProfile);
            this.setHintProfile(hintProfile);
          }
        })
        .catch((err) => {
          console.log("获取视频参数报错", err);
          // this.log.error("获取视频参数失败：" + err);
          this.logList +=
            new Date().Format("yyyy-MM-dd hh:mm:ss") +
            "  error - " +
            `获取视频参数失败： ${err}` +
            "\n";
          let videoProfile = "";
          if (localStorage.getItem("video_quanlity")) {
            videoProfile = localStorage.getItem("video_quanlity");
            console.log("获取缓存中的视频参数：" + videoProfile);
            this.logList +=
              new Date().Format("yyyy-MM-dd hh:mm:ss") +
              "  info - " +
              `获取缓存中的视频参数：${videoProfile}` +
              "\n";
          } else {
            videoProfile = "480p";
          }
          let audioProfile = "";
          if (localStorage.getItem("noise_quanlity")) {
            audioProfile = localStorage.getItem("noise_quanlity");
          } else {
            audioProfile = "standard";
          }
          let hintProfile = "";
          if (localStorage.getItem("coding_quanlity")) {
            hintProfile = localStorage.getItem("coding_quanlity");
          } else {
            hintProfile = "default";
          }
          this.setprofile(videoProfile);
          this.setaudioprofile(audioProfile);
          this.setHintProfile(hintProfile);
        });
    },
    test() {
      // let date = new Date().Format("yyyy-MM-dd-hh");
      if (this.logList) {
        // this.log.info("下载日志");
        this.logList +=
          new Date().Format("yyyy-MM-dd hh:mm:ss") + "  info - 下载日志\n";
        // this.download(date + "-1", this.logList);
      }
    },
    refreshLog() {
      clearInterval(logTimer);
      logTimer = null;
      let currentHour = new Date().getHours();
      console.log("-------------------清空----------------------");
      logTimer = setInterval(() => {
        let refreshHours = new Date().getHours();
        // let refreshMin = new Date().getMinutes();
        // let refreshSec = new Date().getSeconds();
        let intervalNum = refreshHours-currentHour
        //console.log('时间间隔',intervalNum !=0 && intervalNum % 4 == 0)
        //if (refreshMin == "00" && refreshSec == "00") {
        //间隔四小时下载一次日志
        if(intervalNum !=0 && intervalNum % 4 == 0){
          // 指定每天凌晨做的事情
          // let date = new Date().Format("yyyy-MM-dd-hh");
          if (this.logList) {
            // this.log.info("整点下载日志");
            this.logList +=
              new Date().Format("yyyy-MM-dd hh:mm:ss") +
              "  info - 整点下载日志\n";
            // this.download(date + "-1", this.logList);
          }
          console.log("当前的日志数据", this.logList);
          this.logList = "";
        }
      }, 1000);
    },
    aaa() {
      // let date = new Date().Format("yyyy-MM-dd-hh");
      // this.download(date + "-1", this.logList);
    },

    // download(filename, text) {
    //   var element = document.createElement("a");
    //   element.setAttribute(
    //     "href",
    //     "data:text/plain;charset=utf-8," + encodeURIComponent(text) //encodeURIComponent(text)
    //   );
    //   element.setAttribute("download", filename);
    //   //element.href = "D:";
    //   element.style.display = "none";
    //   document.body.appendChild(element);

    //   element.click();
    //   document.body.removeChild(element);
    // },
    //生成记录
    callterminalCreate() {
      console.log(
        "调用新增影像记录接口，生成记录",
        this.joinTelName,
        this.activaterMethod
      );
      // this.log.info(
      //   "调用新增影像记录接口，生成记录",
      //   this.joinTelName,
      //   this.activaterMethod
      // );
      this.logList +=
        new Date().Format("yyyy-MM-dd hh:mm:ss") +
        "  info - 调用新增影像记录接口，生成记录\n";
      console.log(
        "********************调用新增影像记录接口*********************",
        this.callType
      );
      let params = {
        id: 0,
        activateType: this.callType, //影像激活类型1：语音，2：视频
        accountID: this.userInfoDetails.account.tel,
        userID: this.currentUserId,
        activaterID: this.joinUserId, //加入房间的人的userId
        creatTime: new Date().Format("yyyy-MM-dd"),
        updateTime: new Date().Format("yyyy-MM-dd"),
        activaterName: this.joinTelName, //激活者姓名（来源小程序或其他网络登录TRTC 加入房间者账号）
        durations: this.callDurations, //通话时长
        activaterMethod: this.activaterMethod, //激活者方式（小程序或网站）
      };
      terminalCreate(params)
        .then((res) => {
          console.log(res);
          if (res.code == 0) {
            if (this.callType == 2) {
              this.$message.success("新增影像记录成功");
            } else {
              this.$message.success("新增语音记录成功");
            }
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((error) => {
          this.$message.error("新增影像记录失败");
          console.log("错误", error);
        });
    },
    getNetworkStatus() {
      let that = this;
      window.addEventListener("online", function () {
        that.isNetworkOnline = true;
        // that.log.info("网络连接恢复！");
        console.log("网络连接恢复！");
      });
      window.addEventListener("offline", function () {
        that.isNetworkOnline = false;
        //that.leaveRoom();
        // that.log.warn("网络连接中断！");
        console.log("网络连接中断！");
      });
    },
    // getRoomUser() {
    //   let trtcexpiration = JSON.parse(localStorage.trtcexpiration);
    //   let newdate = new Date().Format("yyyy-MM-dd hh:mm:ss");
    //   let trtcdate = new Date(trtcexpiration * 1000).Format(
    //     "yyyy-MM-dd hh:mm:ss"
    //   );
    //   console.log(
    //     "**********判断是否需要重新获取token*********",
    //     newdate,
    //     trtcdate,
    //     newdate >= trtcdate
    //   );
    //   //如果当前时间大于trtctoken失效时间，那么重新获取token
    //   if (newdate >= trtcdate) {
    //     console.log("****************重新获取trtctoken****************");
    //     this.loginTrtc();
    //     this.log.info("重新获取trtc的token");
    //     this.logList +=
    //       new Date().Format("yyyy-MM-dd hh:mm:ss") +
    //       "  info - 重新获取trtc的token\n";
    //   }
    //   let roomList = [];
    //   roomList.push(this.currentUserId);
    //   getTrtcRoomUser(roomList)
    //     .then((res) => {
    //       let data = res.data;
    //       console.log("aaaa", data);
    //       if (data.code == 0) {
    //         // console.log("当前房间人数", data.rooms[0].users.length);
    //         //如果房间已经解散，则重新创建房间
    //         if (data.rooms[0].users.length == 0) {
    //           this.log.info("房间已被解散，重新创建房间");
    //           this.logList +=
    //             new Date().Format("yyyy-MM-dd hh:mm:ss") +
    //             "  info - 房间已被解散，重新创建房间\n";
    //           console.log("房间解散重新创建房间");
    //           this.createTrtc();
    //         }
    //         if (
    //           data.rooms[0].users.length == 1 &&
    //           data.rooms[0].users[0].userid == this.currentUserId
    //         ) {
    //           console.log("房间里面有自己");
    //           this.log.info("联网后房间只有自己");
    //           this.logList +=
    //             new Date().Format("yyyy-MM-dd hh:mm:ss") +
    //             "  info - 联网后房间只有自己\n";
    //           this.leaveRoom();
    //           setTimeout(() => {
    //             this.createTrtc();
    //           }, 4000);
    //           //this.playleaveRoom();
    //         }
    //       } else {
    //         this.log.error("调用trtc接口失败，操作先离房再进房");
    //         this.logList +=
    //           new Date().Format("yyyy-MM-dd hh:mm:ss") +
    //           "  error - 调用trtc接口失败，操作先离房再进房\n";
    //         this.leaveRoom();
    //         setTimeout(() => {
    //           this.createTrtc();
    //         }, 4000);
    //       }
    //     })
    //     .catch((error) => {
    //       this.log.error("联网后调用接口失败" + error);
    //       this.logList +=
    //         new Date().Format("yyyy-MM-dd hh:mm:ss") +
    //         "  error - 联网后调用接口失败\n";
    //       this.leaveRoom();
    //       setTimeout(() => {
    //         this.createTrtc();
    //       }, 4000);
    //     });
    // },
    //打开本地视频
    openLocalVedio() {
      const videoStream = TRTC.createStream({
        userId: this.userInfoDetails.account.tel,
        audio: true,
        video: true,
      });
      let roomprofile = this.profile;
      console.log(
        "**************************当前对讲时视频质量最新*****************************",
        roomprofile
      );
      // 自定义视频分辨率、帧率和码率
      videoStream.setVideoProfile(roomprofile);

      videoStream.initialize().then(() => {
        let hintprofile = this.hintprofile;
        if (hintprofile != "default") {
          //this.localStreamIntercom.setVideoContentHint(hintprofile);
          videoStream.setVideoContentHint(hintprofile);
          console.log(
            "**************************当前对讲时视频编码最新*****************************",
            hintprofile
          );
        }
        const videoTrack = videoStream.getVideoTrack();
        // 将从摄像头采集的视频轨道插入当前已发布的本地流对象LocalStream
        this.localStreamIntercom.addTrack(videoTrack).then(() => {
          // 视频通话开启成功，远端流将会收到‘stream-updated’通知
          //打开本地视频
          this.localStreamIntercom.unmuteVideo();
          console.log("打开本地视频");
          // this.log.info("打开本地视频");
          this.logList +=
            new Date().Format("yyyy-MM-dd hh:mm:ss") +
            "  info - 打开本地视频\n";
        });
      });
    },
    closeLocalVedio() {
      console.log("关闭本地视频流");
      //关闭视频
      this.localStreamIntercom.muteVideo();
      const videoTrack = this.localStreamIntercom.getVideoTrack();
      if (videoTrack) {
        this.localStreamIntercom.removeTrack(videoTrack).then(() => {
          // 关闭视频通话成功，停止videoTrack并释放摄像头资源
          console.log(
            "关闭视频通话成功，停止videoTrack并释放摄像头资源",
            videoTrack
          );
          videoTrack.stop();
          console.log("关闭本地视频，停止videoTrack并释放摄像头资源");
          // this.log.info("关闭本地视频，停止videoTrack并释放摄像头资源");
          this.logList +=
            new Date().Format("yyyy-MM-dd hh:mm:ss") +
            "  info - 关闭本地视频，停止videoTrack并释放摄像头资源\n";
        });
      }
    },
    //切换大屏小屏
    changeScreen() {
      console.log("点击切换大小");
      this.myBigScreen = !this.myBigScreen;
    },
    //离开房间
    leaveRoom() {
      console.log("通话时长", this.callDurations);
      // this.log.info("通话时长:" + this.callDurations);
      this.logList +=
        new Date().Format("yyyy-MM-dd hh:mm:ss") +
        "  info - 通话时长:" +
        this.callDurations +
        "\n";
      this.showCallDialog = false;
      //关闭通话时长计时器
      if (this.callDurationsTimer) {
        window.clearInterval(this.callDurationsTimer);
        this.callDurationsTimer = null;
      }
      window.clearTimeout(callingTimer); //离开房间，关闭60开房倒计时
      callingTimer = null;
      window.clearTimeout(this.twoMinuesTimer); //离开房间，关闭通话两分钟倒计时
      this.twoMinuesTimer = null;
      let that = this;
      console.log("退出房间");
      // that.log.info("开始退出房间");
      let trtcClientIntercom = that.trtcClientIntercom;
      trtcClientIntercom
        .leave()
        .then(() => {
          this.hasRoom = false;
          that.updateCallStatus("idle");
          console.log("退房成功");
          // that.log.info("退房成功");
          that.isShowVedio = false;
          // 停止本地流，关闭本地流内部的音视频播放器
          that.localStreamIntercom.stop();
          // 关闭本地流，释放摄像头和麦克风访问权限
          that.localStreamIntercom.close();
          that.localStreamIntercom = null;
          that.trtcClientIntercom = null;
          that.setisJoinRoom(false);
        })
        .catch((error) => {
          // that.log.warn("退房失败 " + error);
          console.error("退房失败 " + error);
        });
      //创建通话记录
      this.callterminalCreate();
    },
    closeDialog() {
      //关闭弹窗
      this.showCallDialog = false;
    },
    //登录TRTC
    async loginTrtc() {
      const params = {
        acount: "admin_nikoyose_3033654362",
        paswd: "admin_nikoyose_3033654362",
        appid: 1400552732,
      };
      await getTrtcLogin(params).then((res) => {
        if (res.data.code == 0) {
          //存储token
          window.localStorage["trtctoken"] = JSON.stringify(res.data.token);
          //存储token过期时间
          window.localStorage["trtcexpiration"] = JSON.stringify(
            res.data.expiration
          );
        } else {
          this.$message.error(res.error_msg);
        }
      });
    },
    //移除用户
    async removeUser() {
      this.leaveRoom();
      let trtcexpiration = JSON.parse(localStorage.trtcexpiration);
      let newdate = new Date().Format("yyyy-MM-dd hh:mm:ss");
      let trtcdate = new Date(trtcexpiration * 1000).Format(
        "yyyy-MM-dd hh:mm:ss"
      );
      console.log(
        "**********判断是否需要重新获取token*********",
        newdate,
        trtcdate,
        newdate >= trtcdate
      );
      //如果当前时间大于trtctoken失效时间，那么重新获取token
      if (newdate >= trtcdate) {
        console.log("****************重新获取trtctoken****************");
        this.loginTrtc();
        // this.log.info("重新获取trtc的token");
        this.logList +=
          new Date().Format("yyyy-MM-dd hh:mm:ss") +
          "  info - 重新获取trtc的token\n";
      }
      this.isShowVedio = false;
      this.showCallDialog = false;
      let removeparams =
        "roomid=" + this.currentUserId + "&userid=" + this.joinUserId;
      await trtcRemoveUser(removeparams);
      //this.closeLocalVedio(); //关闭本地视频
    },
    //创建trtc
    createTrtc() {
      this.hasOther = false;
      this.hasRoom = true;
      this.updateCallStatus("connected");
      window.clearTimeout(callingTimer);
      callingTimer = null;
      //开房60s 若无人进房，则退出房间
      callingTimer = window.setTimeout(() => {
        if (!this.hasOther) {
          //60s后无人进房 则离开房间
          console.log("计时器到达60s");
          this.leaveRoom();
        }
      }, 60 * 1000);
      console.log("创建TRTC");
      // this.log.info("创建TRTC");
      this.logList +=
        new Date().Format("yyyy-MM-dd hh:mm:ss") + "  info - 创建TRTC\n";
      // if(this.isJoinRoom == true){
      //   console.log('*********************已经进房了并且没有退出*******************')
      //   return
      // }
      let userId = this.currentUserId;
      this.trtcClientIntercom = null;
      // 创建trtc
      this.trtcClientIntercom = TRTC.createClient({
        mode: "rtc", // 通信模式，'rtc'表示实时通信模式
        sdkAppId: config.SDKAppID, // 在腾讯云控制台申请的SDKAppID
        userId: userId, //用户ID
        userSig: genTestUserSig(userId).userSig, //用户签名
        useStringRoomId: true,
      });
      // 注册远程监听
      this.subscribeStream(this.trtcClientIntercom);
      // 公共监听方法----主要是推流方摄像头关闭，音频关闭开启等；下方有说！！
      this.publicMonitor(this.trtcClientIntercom);
      this.joinRoom(this.trtcClientIntercom, this.currentUserId);
    },
    //创建本地音视频流
    createStreams(userId) {
      let localStreamIntercom = null;
      this.localStreamIntercom = null;
      let videoData = false;
      if (this.isShowVedio) {
        videoData = true;
      } else {
        videoData = false;
      }
      localStreamIntercom = TRTC.createStream({
        userId,
        audio: true,
        video: videoData,
      });
      this.micOpen = true; //打开麦克风标识
      this.cameraOpen = true; //打开摄像头标识
      this.localStreamIntercom = localStreamIntercom;
      let audioprofile = this.audioprofile;
      let roomprofile = this.profile;

      console.log(
        "**************************当前对讲时视频质量最初*****************************",
        roomprofile
      );
      console.log(
        "**************************对讲时语音质量*****************************",
        audioprofile
      );
      // 自定义视频分辨率、帧率和码率
      //localStreamIntercom.setVideoProfile(roomprofile);
      //自定义语音质量
      localStreamIntercom.setAudioProfile(audioprofile);
      localStreamIntercom
        .initialize()
        .catch((error) => {
          // this.log.warn("初始化本地流失败");
          this.logList +=
            new Date().Format("yyyy-MM-dd hh:mm:ss") +
            "  warn - 初始化本地流失败\n";
          console.error("初始化本地流失败 " + error);
        })
        .then(() => {
          // this.log.info("初始化本地流成功");
          this.logList +=
            new Date().Format("yyyy-MM-dd hh:mm:ss") +
            "  info - 初始化本地流成功\n";
          console.log("初始化本地流成功");
          localStreamIntercom.play("local_stream_intercom");
          //创建好后才能发布
          this.publishStream(localStreamIntercom, this.trtcClientIntercom);
        });
    },
    //发布本地音视频流
    publishStream(localStreamIntercom, trtcClientIntercom) {
      trtcClientIntercom
        .publish(localStreamIntercom)
        .catch((error) => {
          console.error("本地流发布失败 " + error);
        })
        .then(() => {
          this.roomMqttPublish(); //发送消息，提醒房间已经准备好
          console.log("本地流发布成功");
          // this.localStreamIntercom.muteVideo(); //关闭视频
          // const videoTrack = this.localStreamIntercom.getVideoTrack();
          // if (videoTrack) {
          //   this.localStreamIntercom.removeTrack(videoTrack).then(() => {
          //     // 关闭视频通话成功，停止videoTrack并释放摄像头资源
          //     console.log(
          //       "关闭视频通话成功，停止videoTrack并释放摄像头资源",
          //       videoTrack
          //     );
          //     videoTrack.stop();
          //   });
          // }
        });
    },
    //订阅远端流--加入房间之前
    subscribeStream(trtcClientIntercom) {
      trtcClientIntercom.on("stream-added", (event) => {
        const remoteStream = event.stream;
        console.log("远端流增加：" + remoteStream.getId());
        //订阅远端流
        trtcClientIntercom.subscribe(remoteStream);
      });
    },
    //播放远端流
    playStream(trtcClientIntercom) {
      trtcClientIntercom.on("stream-subscribed", (event) => {
        const remoteStream = event.stream;
        console.log("远端流订阅成功：" + remoteStream.getId());
        // 创建远端流标签，因为id是动态的，所以动态创建，用了v-html
        // const base = `<div id="${
        //   "remote_stream-" + remoteStream.getId()
        // }"  style="width:0.01%;height:0.01%"></div>`;
        let base = null;
        base = `<div id="${
          "remote_stream-" + remoteStream.getId()
        }"  style="width:100%;height:100%"></div>`;
        // base = `<div id="${"remote_stream-" + remoteStream.getId()}"></div>`;
        //如果不进行初始化，会添加多个视频
        this.remoteStream = [];
        this.remoteStream.push(base);
        //做了dom操作 需要使用$nextTick(),否则找不到创建的标签无法进行播放
        this.$nextTick(() => {
          //播放
          remoteStream.play("remote_stream-" + remoteStream.getId());
        });
      });
    },
    //加入房间
    joinRoom(trtcClientIntercom, roomId) {
      //如果已经进房了并且没有退出，则不再重复进
      trtcClientIntercom
        .join({ roomId })
        .catch((error) => {
          console.error("进房失败 " + error);
          // this.log.error("进房失败");
          this.logList +=
            new Date().Format("yyyy-MM-dd hh:mm:ss") + "  error - 进房失败\n";
        })
        .then(() => {
          // this.log.info("进房成功");
          this.logList +=
            new Date().Format("yyyy-MM-dd hh:mm:ss") + "  info - 进房成功\n";
          console.log("**************进房成功******************", roomId);
          this.setisJoinRoom(true);
          //创建本地流
          this.createStreams(this.userInfoDetails.account.tel);
          this.playStream(this.trtcClientIntercom);
        });
    },
    //TRTC事件监听
    publicMonitor(trtcClientIntercom) {
      // Audio/Video Player 状态变化事件。
      trtcClientIntercom.on("player-state-changed", (evt) => {
        console.log("远端流Audio/Video Player 状态变化事件", evt);
      });
      //let that = this;
      // 新增人员
      trtcClientIntercom.on("peer-join", (evt) => {
        //this.showCallDialog = true;
        // //打开麦克风
        // this.localStreamIntercom.unmuteAudio()
        this.callType = 1; //默认对方未开启摄像头
        console.log("新增人员", evt);
        // this.log.info("新增人员" + evt.userId);
        this.logList +=
          new Date().Format("yyyy-MM-dd hh:mm:ss") +
          "  info - 新增人员" +
          evt.userId +
          "\n";
        this.hasOther = true;
        this.joinUserId = evt.userId;
        if (callingTimer) {
          window.clearTimeout(callingTimer); //有人进房，关闭60s离房倒计时
          callingTimer = null;
        }
        // if (this.addUserTimer) {
        //   clearTimeout(this.addUserTimer);
        //   this.addUserTimer = null;
        // }
        if (this.twoMinuesTimer) {
          window.clearTimeout(this.twoMinuesTimer);
          this.twoMinuesTimer = null;
        }
        this.twoMinuesTimer = window.setTimeout(() => {
          this.leaveRoom();
        }, 2 * 60 * 1000);
        // this.addUserTimer = setTimeout(() => {
        //   this.callterminalCreate();
        // }, 8000);
        if (this.callDurationsTimer) {
          window.clearInterval(this.callDurationsTimer); //有人进房，关闭60s离房倒计时
          this.callDurationsTimer = null;
        }
        this.callDurations = 0;
        this.callDurationsTimer = window.setInterval(() => {
          this.callDurations++;
        }, 1000);
      });
      // 删减人员
      trtcClientIntercom.on("peer-leave", (evt) => {
        // this.log.info("对方离开房间");
        this.logList +=
          new Date().Format("yyyy-MM-dd hh:mm:ss") + "  info - 对方离开房间\n";
        console.log("删减人员", evt);
        //对方离开，自己挂断
        this.showCallDialog = false;
        this.isShowVedio = false;
        //this.closeLocalVedio(); //关闭本地视频
        this.leaveRoom(); //对方离开房间，则自己也退房
      });
      // 推流方关闭音频
      trtcClientIntercom.on("mute-audio", (evt) => {
        console.log("推流方关闭音频", evt);
      });
      // 推流方开启音频
      trtcClientIntercom.on("unmute-audio", (evt) => {
        // this.log.info("对方开启音频");
        this.logList +=
          new Date().Format("yyyy-MM-dd hh:mm:ss") + "  info - 对方开启音频\n";
        console.log("推流方开启音频", evt);
      });
      // 远端流启用视频
      trtcClientIntercom.on("unmute-video", (evt) => {
        this.isShowVedio = true;
        //this.openLocalVedio();
        this.callType = 2;
        // this.log.info("对方开启视频");
        this.logList +=
          new Date().Format("yyyy-MM-dd hh:mm:ss") + "  info - 对方开启视频\n";
        console.log("远端流启用视频事件", evt);
      });
      // 远端流禁用视频
      trtcClientIntercom.on("mute-video", (evt) => {
        this.callType = 1;
        // this.log.info("对方禁用视频");
        this.logList +=
          new Date().Format("yyyy-MM-dd hh:mm:ss") + "  info - 对方禁用视频\n";
        console.log("远端流禁用视频事件", evt);
      });
      //用户被踢出房间
      trtcClientIntercom.on("client-banned", (evt) => {
        console.log("用户被踢出房间事件", evt);
        // this.log.info("触发被踢事件");
        this.logList +=
          new Date().Format("yyyy-MM-dd hh:mm:ss") + "  info - 触发被踢事件\n";
        this.updateCallStatus("idle");
        this.leaveRoom();
      });
      //错误事件
      trtcClientIntercom.on("error", (evt) => {
        console.log("错误事件", evt);
        // this.log.error("TRTC发生错误事件:" + evt);
        this.logList +=
          new Date().Format("yyyy-MM-dd hh:mm:ss") +
          "  error - TRTC发生错误事件\n";
        //this.getRoomUser();
      });
      trtcClientIntercom.on("connection-state-changed", (event) => {
        console.log(
          `当前用户的连接状态  prevState: ${event.prevState}, state: ${event.state}`
        );
        // this.log.debug(
        //   `当前用户的TRTC连接状态  prevState: ${event.prevState}, state: ${event.state}`
        // );
        this.logList +=
          new Date().Format("yyyy-MM-dd hh:mm:ss") +
          "  debug - " +
          `当前用户的TRTC连接状态  prevState: ${event.prevState}, state: ${event.state}` +
          "\n";
        if (
          event.prevState == "RECONNECTING " &&
          event.state == "DISCONNECTED"
        ) {
          console.log("TRTC自动重连失败");
          //this.getRoomUser();
        }
      });

      trtcClientIntercom.on("network-quality", (event) => {
        // this.log.debug(
        //   `TRTC上行网络质量 ${event.uplinkNetworkQuality}, TRTC下行网络质量 ${event.downlinkNetworkQuality}`
        // );
        // this.logList +=
        //   new Date().Format("yyyy-MM-dd hh:mm:ss") +
        //   "  debug - " +
        //   `TRTC上行网络质量 ${event.uplinkNetworkQuality}, TRTC下行网络质量 ${event.downlinkNetworkQuality}` +
        //   "\n";
        // console.log(
        //   `network-quality, 上行网络质量 ${event.uplinkNetworkQuality}`
        // );
        this.localNetworkQuality = event.uplinkNetworkQuality;
        // 自 v4.10.3 支持获取上、下行的 RTT 及丢包率
        //console.log(`uplink rtt:${event.uplinkRTT} loss:${event.uplinkLoss}`);
        // console.log(
        //   `downlink rtt:${event.downlinkRTT} loss:${event.downlinkLoss}`
        // );
      });
    },
  },
};
</script>
<style scoped>
.search-user-container {
  width: 400px;
  margin: 10px auto 0;
  padding: 1px;
}
.search-section {
  display: flex;
  flex-direction: row;
}
.search-user-btn {
  margin-left: 10px;
}
.search-user-list {
  padding-top: 20px;
}
.search-user-list-title {
  margin-top: 20px;
  font-size: 18px;
  text-align: left;
}
.user-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
}
.video-call-section-header {
  font-size: 24px;
}
.user-item-info {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.user-item-avatar-wrapper img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.user-item-username {
  margin-left: 20px;
}
/* @media screen and (max-width: 767px) {
    .search-user-container {
      width: 90%;
    }
  } */
.box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  flex-wrap: wrap;
}
.containerBox {
  background-color: rgb(43, 46, 59);
  width: 29rem;
  height: 36rem;
  border-radius: 0.7rem;
  margin-top: -2rem;
}
.callTitle {
  background: linear-gradient(to top, #949191, #ffffff);
  -webkit-background-clip: text;
  color: transparent;
  font-weight: bold;
  padding: 0.5rem 0 0.1rem;
}
.iconBox {
  display: flex;
  justify-content: center;
  margin-top: -7.5rem;
}
.callIcon {
  margin-left: 0rem;
}
.hangupIcon {
  margin-top: 0.2rem;
  margin-left: 7rem;
}
.circleImage {
  width: 10rem;
  height: 10rem;
  background: aliceblue;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.circleImage img {
  width: 8rem;
}
.centerImage {
  width: 12rem;
  height: 12rem;
  background: #31333a;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  margin-top: 4rem;
}
.statusText {
  color: white;
  text-align: center;
  font-size: 1.3rem;
  margin-top: 1rem;
}
.timeText {
  color: white;
  text-align: center;
  font-size: 1.3rem;
  margin-top: 0.2rem;
}
.callBox {
  position: absolute;
  top: 0rem;
  left: 0rem;
  width: 100%;
  height: 100%;
}
.nocallBox {
  position: absolute;
  top: 0rem;
  left: 0rem;
  width: 100%;
  height: 100%;
}
.testBox {
  position: absolute;
  top: 6rem;
  left: 3rem;
}
.testContainer {
  position: absolute;
  top: 8rem;
  left: 3rem;
  line-height: 1.5rem;
}
.online {
  background-color: #13ce66;
  padding: 0.3rem 0.5rem;
  border-radius: 0.3rem;
  color: white;
}
.disconnect {
  background-color: red;
  padding: 0.3rem 0.5rem;
  border-radius: 0.3rem;
  color: white;
}
.topIcon {
  position: absolute;
  top: 4rem;
  right: 0rem;
}
.topIcon img {
  width: 3.5rem;
  height: 3.5rem;
  margin-right: 2rem;
}
.dialogContainer {
  width: 22rem;
  height: 13rem;
  background-color: white;
  border-radius: 0.7rem;
  position: relative;
}
.dialogTitle {
  padding: 0.6rem 1rem 0rem;
  text-align: left;
  font-size: 1.5rem;
}
.dialogText {
  margin-top: 2rem;
  color: black;
  line-height: 1.8rem;
}
.dialogButtonBox {
  margin-top: 1rem;
}
.allcallBox {
  width: 100%;
  height: 100%;
}
.vedioCalling {
  width: 100%;
  height: 100%;
  background: linear-gradient(
    to top,
    rgb(184, 213, 217),
    rgb(127 144 175),
    rgb(100 123 166),
    rgb(60, 124, 174)
  );
  /* background-repeat: no-repeat;
    background-size: cover;
    background-image: url('../../assets/images/call/callBackground.jpeg'); */
}
.callingImageContainer {
  padding-top: 11rem;
}
.vediocircleImage {
  width: 10rem;
  height: 10rem;
  background: aliceblue;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: auto;
  margin-bottom: 2rem;
}
.vediocircleImage img {
  width: 8rem;
}
.vedioiconBox {
  display: flex;
  position: absolute;
  bottom: 4rem;
  left: 41.3rem;
}
.callBoxvedio {
  position: absolute;
  top: 0rem;
  left: 0rem;
  width: 100%;
  height: 100%;
}
.local-stream {
  width: 0.01%;
  height: 0.01%;
}
.local-stream-audio {
  width: 0.01%;
  height: 0.01%;
}
.local-stream-vedio {
  width: 47rem;
  height: 52%;
  position: absolute;
  left: 26.5rem;
  top: 20%;
  z-index: 1;
}
.distant-stream-audio {
  width: 0.01%;
  height: 0.01%;
}
.distant-stream-vedio {
  width: 15.5rem;
  height: 24%;
  position: absolute;
  left: 58rem;
  top: 20%;
  z-index: 2;
}

.vedioInfo {
  position: absolute;
  right: 1.5rem;
}
.distant-vedio-box {
  height: 100%;
}
.cameraIcon {
  width: 3.8rem;
  height: 3.8rem;
  background-color: #e6e6e6;
  border-radius: 50%;
  margin-left: 2rem;
  cursor: pointer;
}
.micsmallImage {
  width: 2rem;
  cursor: pointer;
  margin-top: 1rem;
}
.callIconConnected {
  width: 3.9rem;
  cursor: pointer;
}
.nocallIconConnected {
  width: 5.8rem;
  cursor: pointer;
}
.hangupVedio {
  margin-left: 2rem;
}
.videoCallingStatusText {
  color: white;
  text-align: right;
  font-size: 1.3rem;
  padding-top: 1.5rem;
  padding-right: 1.5rem;
}
.loadingIcon {
  width: 8rem;
  height: 8rem;
  /* line-height: 100%; */
}
.loadingText {
  font-size: 1.6rem;
}
.dialogBox {
  width: 50rem;
  height: 60%;
  background-color: white;
  position: absolute;
  left: 25rem;
  top: 50%;
  transform: translateY(-50%);
  border-radius: 0.5rem;
}
.vediodialogBox {
  width: 50rem;
  height: 70%;
  background-color: white;
  position: absolute;
  left: 25rem;
  top: 50%;
  transform: translateY(-50%);
  border-radius: 0.5rem;
}
.dialogBigBox {
  z-index: 1;
  width: 100%;
  height: 100%;
  background-color: #0000006b;
  position: absolute;
  left: 0rem;
  top: 0rem;
}
</style>
  